package com.ruoyi.alert.consumer;

import com.ruoyi.alert.domain.Alert;
import com.ruoyi.alert.service.DingTalkService;
import com.ruoyi.alert.service.impl.AlertServiceImpl;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;

import java.io.IOException;


@Component
public class AlertConsumer {

    @Autowired
    private AlertServiceImpl alertService;

    @Autowired
    private DingTalkService dingTalkService;

    @RabbitListener(queues = "alarm.queue")
    public void processAlarm(Alert message, Channel channel, Message amqpMessage) throws IOException {
        try {
            System.out.println("接收到警报消息: " + message);
            boolean isDuplicate = alertService.isDuplicate(message);
            if (!isDuplicate) {
                System.out.println("准备发送钉钉消息...");
                // 钉钉通知
                dingTalkService.sendAlarm(message);
                alertService.markAsSent(message);
                channel.basicAck(amqpMessage.getMessageProperties().getDeliveryTag(), false);

            }
            System.out.println("消息去重检查结果：" + alertService.isDuplicate(message));
        }  catch (Exception e) {
            // 处理失败，拒绝消息（根据需求选择是否重新入队）
            channel.basicNack(amqpMessage.getMessageProperties().getDeliveryTag(), false, false);
            throw new RuntimeException("处理警报失败", e);
        }
    }
}